package com.ywu.file.sys.sdk.utils;

import com.ywu.common.gson.GsonUtils;
import com.ywu.common.result.CommonResult;
import com.ywu.file.sys.sdk.config.YwuFileSystemConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 * @ClassName RestTemplateUtil
 * @Description TODO
 * @Author GroundDemo
 * @Date 2024/9/28 11:36
 * @Version 1.0
 **/
@Component
@Slf4j
public class YfsRestTemplateUtil {
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private YwuFileSystemConfig config;

    public String execUpload(Map<String, String> headerMap, MultiValueMap<String, Object> formMap) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        Set<String> keys = headerMap.keySet();
        for (String key : keys) {
            String head = headerMap.get(key);
            headers.set(key, head);
        }
        HttpEntity<MultiValueMap<String, Object>> files = new HttpEntity<>(formMap, headers);
        String resStr = restTemplate.postForObject(config.getDoUploadUrl(), files, String.class);
        CommonResult commonResult = GsonUtils.deserialize(resStr, CommonResult.class);
        if (Objects.isNull(commonResult)) {
            return null;
        }
        if (commonResult.getCode().equals("200")) {
            return (String) commonResult.getData();
        }
        return null;
    }

    /**
    * @Author GroundDemo
    * @Description 执行下载请求
    * @Date 13:27 2024/10/11
    * @Param [headerMap, fileId]
    * @return java.io.File
    **/
    public String execDownload(Map<String, String> headerMap, String fileId) {
        HttpHeaders headers = new HttpHeaders();
        Set<String> keys = headerMap.keySet();
        for (String key : keys) {
            String head = headerMap.get(key);
            headers.set(key, head);
        }
        headers.setContentType(MediaType.APPLICATION_JSON);
        // 构建URL
        String execUrl = config.getDoDownloadUrl() + "/" + fileId;
        // 构建请求体信息
        HttpEntity<MultiValueMap<String, Object>> req = new HttpEntity<>(null, headers);
        // 执行URL
        ResponseEntity<byte[]> responseEntity = restTemplate.exchange(execUrl, HttpMethod.GET, req, byte[].class);
        // 获取响应体，解析响应数据，将字节码数据写入文件
        byte[] body = responseEntity.getBody();
        if (Objects.isNull(body)) {
            log.error("responseEntity is null");
            return null;
        }
        File file = new File(config.getDownloadTempPath());
        if (!file.exists() && !file.mkdirs()) {
            log.error("file dir make error");
            return null;
        }
        // 构建目标文件路径
        String destFilePath = config.getDownloadTempPath() + File.separator + fileId;
        try (FileOutputStream fos = new FileOutputStream(destFilePath)) {
            // 将byte数组写入文件
            fos.write(body);
        } catch (IOException e) {
            log.error("file write error {}", e.getMessage());
            return null;
        }
        return destFilePath;
    }
}
